<?php
/* 解析列表定义规则*/
function get_list_field($data, $grid)
{
    // 获取当前字段数据
    foreach ($grid['field'] as $field) {
        $array = explode('|', $field);
        $temp = $data[$array[0]];
        // 函数支持
        if (isset($array[1])) {
            $temp = call_user_func($array[1], $temp);
        }
        $data2[$array[0]] = $temp;
    }
    if (!empty($grid['format'])) {
        $value = preg_replace_callback('/\[([a-z_]+)\]/', function ($match) use ($data2) {
            return $data2[$match[1]];
        }, $grid['format']);
    } else {
        $value = implode(' ', $data2);
    }

    // 链接支持
    if ('title' == $grid['field'][0] && '目录' == $data['type']) {
        // 目录类型自动设置子文档列表链接
        $grid['href'] = '[LIST]';
    }
    if (!empty($grid['href'])) {
        $links = explode(',', $grid['href']);
        foreach ($links as $link) {
            $array = explode('|', $link);
            $href = $array[0];
            if (preg_match('/^\[([a-z_]+)\]$/', $href, $matches)) {
                $val[] = $data2[$matches[1]];
            } else {
                $show = isset($array[1]) ? $array[1] : $value;
                // 替换系统特殊字符串
                $href = str_replace(
                    array('[DELETE]', '[EDIT]', '[LIST]'),
                    array('setstatus?status=-1&ids=[id]',
                        'edit?id=[id]&model=[model_id]&cate_id=[category_id]',
                        'index?pid=[id]&model=[model_id]&cate_id=[category_id]'),
                    $href);

                // 替换数据变量
                $href = preg_replace_callback('/\[([a-z_]+)\]/', function ($match) use ($data) {
                    return $data[$match[1]];
                }, $href);

                $val[] = '<a href="' . url($href) . '">' . $show . '</a>';
            }
        }
        $value = implode(' ', $val);
    }
    return $value;
}

// 获取属性类型信息
function get_attribute_type($type = '')
{
    // TODO 可以加入系统配置
    static $_type = array(
        'num' => array('数字', 'int(10) UNSIGNED NOT NULL'),
        'string' => array('字符串', 'varchar(255) NOT NULL'),
        'textarea' => array('文本框', 'text NOT NULL'),
        'date' => array('日期', 'int(10) NOT NULL'),
        'datetime' => array('时间', 'int(10) NOT NULL'),
        'bool' => array('布尔', 'tinyint(2) NOT NULL'),
        'select' => array('枚举', 'char(50) NOT NULL'),
        'radio' => array('单选', 'char(10) NOT NULL'),
        'checkbox' => array('多选', 'varchar(100) NOT NULL'),
        'editor' => array('编辑器', 'text NOT NULL'),
        'picture' => array('上传图片', 'int(10) UNSIGNED NOT NULL'),
        'file' => array('上传附件', 'int(10) UNSIGNED NOT NULL'),
    );
    return $type ? $_type[$type][0] : $_type;
}

/**
 * 权限验证
 * @param null $name
 * @param null $path
 * @param string $relation
 * @return bool
 */
function auth_check($name = null, $path = null, $relation = 'or')
{
    if ($path) {
        $name = strtolower($path . $name);
    } else {
        $request = request();
        $module = $request->module();
        $controller = $request->controller();
        $name = strtolower($module . "/" . $controller . "/" . $name);
    }

    return cmf_auth_check(cmf_get_current_admin_id(), $name, $relation);
}

/**
 * 获取所有部门id
 * @param $gids
 * @param bool $flag
 * @return array|string
 */
function getGroups($gids, $flag = true)
{
    is_array($gids) && $gids = implode(',', $gids);
    $ids = db('department')->where([
        'parent_id' => [
            'in', $gids
        ]
    ])->column('id');

    if (!$ids) {
        if ($flag) {
            return $gids;
        } else {
            return '';
        }
    }
    $ids = implode(',', $ids);

    $id = getGroups($ids, false);
    if ($id) {
        $ids = $ids . ',' . $id;
    }

    if ($flag) {
        return $gids . ',' . $ids;
    } else {
        return $ids;
    }
}

/**
 * 获取用户
 * @param $gids
 * @return string
 */
function getUsers($gids)
{
    is_array($gids) && $gids = implode(',', $gids);
    $users = db('department_user')->where([
        'dep_id' => [
            'in', $gids
        ]
    ])->column('user_id');
    return implode(',', $users);
}

/**
 * 不验证方法
 * @return bool
 */
function auth_public()
{
    $request = request();
    $public = [
        'select',
        'check',
    ];
    if (in_array($request->action(), $public)) {
        return true;
    }
    return false;
}

/**
 * 用户所属部门
 * @param $uid
 * @return array
 */
function get_user_group($uid)
{
    return db('department_user')->where([
        'user_id' => $uid
    ])->column('dep_id');
}

/**
 * 获取当前用户所有部门id
 * @return array|string
 */
function get_departments()
{
    $admin_id = cmf_get_current_admin_id();
    if ($admin_id != 1) {
        return getUsersGroup($admin_id);
    }
    return '';
}

/**
 * 获取部门管理权限
 * @param $role_id
 * @return array
 */
function get_show_department($role_id)
{
    $result = db('role')
        ->alias('role')
        ->join('__ROLE_DEPARTMENT__ role_department','role.id = role_department.role_id','left')
        ->where(['role.id' => ['in',$role_id]])
        ->field('role.department_id as id,show_department')
        ->select();
    return $result;
}

/**
 * 获取属性权限
 * @param $role_id
 * @return array
 */
function get_role_department($role_id, $field)
{
    $result = db('role')
        ->alias('role')
        ->join('__ROLE_DEPARTMENT__ role_department', 'role.id = role_department.role_id', 'left')
        ->where(['role.id' => ['in', $role_id]])
        ->field('role.id,' . $field)
        ->select();
    return $result;
}

/**
 * @return object
 */
function get_view()
{
    $cmfAdminThemePath    = config('cmf_api_theme_path');
    $cmfAdminDefaultTheme = config('cmf_api_default_theme');

    $themePath = "{$cmfAdminThemePath}{$cmfAdminDefaultTheme}";

    $root = cmf_get_root();

    //使cdn设置生效
    $cdnSettings = cmf_get_option('cdn_settings');
    if (empty($cdnSettings['cdn_static_root'])) {
        $viewReplaceStr = [
            '__ROOT__'     => $root,
            '__TMPL__'     => "{$root}/{$themePath}",
            '__STATIC__'   => "{$root}/static",
            '__WEB_ROOT__' => $root
        ];
    } else {
        $cdnStaticRoot  = rtrim($cdnSettings['cdn_static_root'], '/');
        $viewReplaceStr = [
            '__ROOT__'     => $root,
            '__TMPL__'     => "{$cdnStaticRoot}/{$themePath}",
            '__STATIC__'   => "{$cdnStaticRoot}/static",
            '__WEB_ROOT__' => $cdnStaticRoot
        ];
    }

    $viewReplaceStr = array_merge(config('view_replace_str'), $viewReplaceStr);
    config('template.view_base', "$themePath/");
    config('view_replace_str', $viewReplaceStr);
    $view = \think\View::instance(config('template'), config('view_replace_str'));
    return $view;
}